// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package mobile

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
	"server/app/lib/authorizer"
)

// Logic
// 修改手机号.
type Logic struct {
	auth            *authorizer.Authentication
	current, target *models.UserMobiles
	fetched         kind.Mobile
	request         *Request
	response        *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	// 1. 校验入参.
	if err = validator.Json(i, o.request); err != nil {
		return
	}

	// 2. 鉴权信息.
	o.auth = authorizer.New().Get(i)
	return
}

// Run
// 处理过程.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err           error
		found, has    bool
		list          []*models.UserMobiles
		mobileService = services.NewUserMobilesService()
		res           = result.New()
	)

	// 1. 读取绑定.
	//    列出用户账号下绑定的手机号列表(可能有多个, 如微小程序、支付宝小程序等).
	if list, err = mobileService.Dao.ListByMap(ctx, map[string]any{
		"user_id": o.auth.UserId,
	}); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 校验绑定.
	//    若列表非空则遍历列表, 用户提交的手机号必须列表中的任一手机号匹配, 表示用户申请
	//    修改手机号时, 输入的修改前手机号是正确的.
	if len(list) > 0 {
		found = false

		// 2.1 遍历号码.
		for _, item := range list {
			if item.Mobile.String() == o.request.Mobile {
				found = true
				o.current = item
			}
		}

		// 2.2 暂未绑定.
		//     未找到匹配的手机号.
		if !found {
			return res.WithError(errs.ErrUserMobileNotBind)
		}
	}

	// 3. 读取号码.
	//    使用Code到微信获取最新的手机号码.
	if o.fetched, err = lib.Weixin.GetMobile(ctx, o.request.Code); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 4. 校验号码.
	//    检查从微信读取的号码是否在数据库中已存在.
	if o.target, has, err = mobileService.Dao.GetBy(ctx, "mobile", o.fetched.String()); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	} else if has && o.target.UserId.IsBound() {
		return res.WithError(errs.ErrUserMobileBounded)
	}

	// 5. 保存绑定.
	if err = db.Transaction(ctx, o.RunUpdate); err != nil {
		return res.WithError(err)
	}

	// 6. 完成更新.
	o.response.Mobile = o.fetched.Mask()
	o.response.UserId = o.auth.UserId
	return res.With(o.response)
}

func (o *Logic) RunUpdate(ctx context.Context, sess *db.Session) (err error) {
	var service = services.NewUserMobilesService(sess)

	// 1. 解绑.
	if o.current != nil {
		if _, err = service.Dao.UpdateFieldsById(ctx, map[string]any{
			"user_id":          0,
			"released_user_id": o.auth.UserId,
		}, o.current.Id); err != nil {
			err = errs.ErrDatabaseQuery
			return
		}
	}

	// 2. 绑定.
	if o.target != nil {
		// 2.1 更新.
		if _, err = service.Dao.UpdateFieldsById(ctx, map[string]any{
			"user_id": o.auth.UserId,
		}, o.target.Id); err != nil {
			err = errs.ErrDatabaseQuery
			return
		}
	} else {
		// 2.2 新增.
		if o.target, err = service.Dao.AddByStruct(ctx, &models.UserMobiles{
			Mobile: o.fetched,
			UserId: o.auth.UserId,
		}); err != nil {
			err = errs.ErrDatabaseQuery
			return
		}
	}

	// 3. 同步.
	if _, err = services.NewUsersService(sess).Dao.UpdateFieldsById(ctx, map[string]any{
		"mobile": o.fetched.Mask(),
	}, o.auth.UserId); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}
